package com.lee.rabbitmq.transaction;

import com.lee.rabbitmq.util.RabbitMqUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;

/**
 * 使用事务发送消息
 *
 * @author Lee
 * @createDate 2021/12/15 15:17
 */
public class Send {
    public static void main(String[] args) {
        Connection connection = RabbitMqUtil.getConnection();
        Channel channel = null;
        try {
            channel = connection.createChannel();
            //声明队列
            channel.queueDeclare("transactionQueue",true,false,false,null);


            channel.exchangeDeclare("directTransactionExchange","direct",true);


            channel.queueBind("transactionQueue","directTransactionExchange","transactionRoutingKey");
            String message = "事务测试消息1！";
            String message2 = "事务测试消息2！";

            /**
             * 启动一个事务，启动事务以后所有写入到队列中的消息
             * 必须显示的调用txcommit()提交事务或txRollback()回滚事务
             */
            channel.txSelect();
            channel.basicPublish("directTransactionExchange","transactionRoutingKey",null,message.getBytes("utf-8"));
            channel.basicPublish("directTransactionExchange","transactionRoutingKey",null,message2.getBytes("utf-8"));

            /**
             * 提交事务，如果我们调用txSelect()方法启动了事务，那么必须显示调用事务的提交
             * 否则消息不会真正地写入到队列，提交时以后会将内存中的消息写入队列并释放内存
             */
            channel.txCommit();
            System.out.println("消息发送成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            RabbitMqUtil.close(connection,channel);
        }
    }
}
